<template>
  <div class="legal-advice-bottom-container" ref="legalAdviceBottom">
    <div class="other">
      <div class="corporate-counsel-consult" @click="handleService">
        <span class="corporate-counsel-consult-bg"></span>
        <span>公司律师人工咨询</span>
      </div>
      <div class="opinions-sugges" @click="handleSuggestions">
        <span class="opinions-sugges-bg"></span>
        <span>意见建议</span>
      </div>
    </div>
    <div class="ask-question">
      <span class="switch-voice-btn" @click="handleSwitchImg">
        <em class="iconfont icon-yuyin" v-show="switchShowImg" />
        <em class="iconfont icon-jianpan1" v-show="!switchShowImg" />
      </span>
      <span class="inp" v-show="switchShowImg"
        ><input
          type="text"
          placeholder="请输入您的问题"
          v-model.trim="inpValue"
          @keyup.enter="handleSendQuestion"
          @focus="handleFocusEvent"
          @blur="handleBlurEvent"
      /></span>
      <span
        class="send-inp"
        :class="{ 'send-inp-active': inpValue }"
        v-show="switchShowImg"
        @click="handleSendQuestion"
        >发送</span
      >
      <span
        class="voice-btn"
        v-show="!switchShowImg"
        @touchstart="handleTouchstart"
        @touchend="handleTouchend"
        >{{ repressSendText }}</span
      >
    </div>
  </div>
</template>

<script>
import { Toast, manualConsultationUrl } from "@/utils";
const VOICE_PROMPTS = "对不起!没听清，请再说一遍!"; //语音提示语
export default {
  name: "LegalAdviceBottom",
  data() {
    return {
      inpValue: "", //输入框内容
      switchShowImg: true, //true -> 显示语音 false -> 显示键盘（输入框）
      sendInpActive: false, //发送按钮背景颜色
      repressSendText: "按住  说话", //按住发送文本切换
    };
  },
  mounted() {
    //阻止底部栏默认事件
    this.$refs.legalAdviceBottom.addEventListener(
      "touchmove",
      function (e) {
        e.preventDefault();
      },
      { passive: false }
    );
  },
  methods: {
    /**
     * 切换语音或输入框
     */
    handleSwitchImg() {
      this.switchShowImg = !this.switchShowImg;
    },
    /**
     * 点击发送按钮，将输入数据传递给父组件
     */
    handleSendQuestion() {
      const len = this.inpValue.length;

      //输入内容长度限制
      if (len > 0 && len <= 50) {
        this.$emit("handleSendQuestion", this.inpValue);
        this.inpValue = "";
        return;
      }

      Toast.fail("发送的内容不能超过50个字符");
    },

    /**
     * 发送语音 按下事件
     */
    handleTouchstart() {
      this.repressSendText = "松开  结束";
      this.startVoice();
    },

    /**
     * 发送语音 抬起事件
     */
    handleTouchend() {
      this.repressSendText = "按住  说话";
      this.stopVoice();
    },

    /**
     * 监听语音
     */
    handleDevicereadyVoice() {
      try {
        cordova.plugins.mocha.plugin.audioToText.startRecord(
          "startRecord",
          (data) => {
            //没有接收到语音 提示
            if (!data) {
              Toast.fail(VOICE_PROMPTS);
              return;
            }

            //接收到了
            const newData = JSON.parse(data);
            //是否有文本内容
            const isTextCon = newData.hasOwnProperty("text");
            if (isTextCon && newData.text) {
              this.voiceSend(newData.text);
            } else if (
              !newData.hasOwnProperty("isDisconnect") ||
              !newData.isDisconnect ||
              (isTextCon && !newData.text)
            ) {
              Toast.fail(VOICE_PROMPTS);
            }

            newData.isDisconnect &&
              cordova.plugins.mocha.plugin.audioToText.disconnectWebSocket();
          },
          (error) => {
            const errorInfo =
              error == "无录音权限"
                ? "对不起!您无录音权限!"
                : "启动录音错误" + error;
            Toast.fail(errorInfo);
            this.stopVoice();
            cordova.plugins.mocha.plugin.audioToText.disconnectWebSocket();
          }
        );
      } catch (error) {
        Toast.fail("启动语音录音错误:" + error.message);
      }
    },

    /**
     * 开始启动语音录音功能
     */
    startVoice() {
      Toast.customToast({
        message: "语音进行中...",
        duration: 0,
      });

      document.removeEventListener(
        "deviceready",
        this.handleDevicereadyVoice,
        false
      );
      document.addEventListener(
        "deviceready",
        this.handleDevicereadyVoice,
        false
      );
    },

    /**
     * 停止语音录音功能
     */
    stopVoice() {
      Toast.closeLoading();
      Toast.customToast({
        message: "结束语音",
        duration: 1000,
      });

      try {
        cordova.plugins.mocha.plugin.audioToText.stopRecord(
          "stopRecord",
          null,
          function (error) {
            Toast.fail("停录音错误:" + error);
          }
        );
      } catch (error) {
        Toast.fail("停止语音录音错误:" + error.message);
      }
    },

    /**
     * 发送语音
     */
    voiceSend(text) {
      this.inpValue = text;
      this.handleSendQuestion();
    },

    /**
     * 输入框聚焦时，让底部菜单栏顶起
     */
    handleFocusEvent() {
      setTimeout(() => {
        document.documentElement.scrollTop =
          document.documentElement.scrollHeight;
      }, 1000);
    },

    /**
     * 输入框失焦时，让底部菜单栏回到原处
     */
    handleBlurEvent() {
      this.$refs.legalAdviceBottom.style.bottom =
        document.documentElement.scrollTop = 0;
    },

    /**
     * 跳转到意见建议页面
     */
    handleSuggestions() {
      this.$router.push({ name: "OpinionsSuggestions" });
    },

    /**
     * 跳转到人工客服咨询
     */
    handleService() {
      MXCommon.openUrlPage(manualConsultationUrl());
    },
  },
};
</script>

<style lang="less" scoped>
@import url("~@/assets/styles/legalAdvice/legalAdviceBottom.less");
</style>